<template>
  <div>
    <van-cell-group>
      <van-cell
        title="课程类型"
        is-link
        :value="displayCourse.type ? displayCourse.type : '请选择课程类型'"
        :value-class="displayCourse.type ? 'cell-value' : ''"
        @click="showType = true"/>
      <van-cell title="课程名称">
        <van-field v-model="course.kcname" placeholder="请输入课程名称"/>
      </van-cell>
      <van-cell title="学生姓名">
        <van-field v-model="displayCourse.students" placeholder="请选择上课学生" disabled @click="toSelectStudent"/>
      </van-cell>
      <van-cell
        title="重复方式"
        is-link
        :value="displayCourse.repeat ? displayCourse.repeat : '请选择重复方式'"
        :value-class="displayCourse.repeat ? 'cell-value' : ''"
        @click="showRepeat = true"/>
      <div class="edit-times">
        <van-cell title="上课时间">
          <div class="times">
            <div class="time start-time" @click="toSelectTime('start')">
              <p>{{ displayTime.start[0] }}</p>
              <p>{{ displayTime.start[1] }}</p>
            </div>
            <img src="../../../../assets/img/icon-arrow.png" alt="">
            <div class="time end-time" @click="toSelectTime('end')">
              <p>{{ displayTime.end[0] }}</p>
              <p>{{ displayTime.end[1] }}</p>
            </div>
          </div>
        </van-cell>
      </div>
      <van-cell
        title="所在地区"
        is-link
        :value="course.skplace ? course.skplace : '请选择上课所在省市区'"
        :value-class="course.skplace ? 'cell-value' : ''"
        @click="showAddress = true"/>
      <van-cell title="详细地址">
        <van-field v-model="course.dqplace" rows="1" autosize type="textarea" placeholder="请输入上课详细地址"/>
      </van-cell>
      <van-cell title="已缴费课时">
        <van-field v-model="course.class_hour" placeholder="请输入已缴费课时"/>
      </van-cell>
    </van-cell-group>
    <div class="btns">
      <van-button hairline type="info" plain  @click="toAddCourse">临时调课</van-button>
      <!-- <van-button hairline type="info" plain @click="cancel">取消</van-button> -->
      <!-- <van-button type="info" @click="toAddCourse">保存</van-button> -->
    </div>

    <!-- actions -->
    <!-- 课程类型action -->
    <van-action-sheet title="请选择课程类型" v-model="showType" :actions="typeActions" @select="onSelectType" :round="false"/>

    <!-- 重复方式 -->
    <van-action-sheet title="请选择重复方式" v-model="showRepeat" :actions="repeatActions" @select="onSelectRepeat" :round="false"/>

    <!-- 所在地区 -->
    <van-popup
      v-model="showAddress"
      position="bottom">
      <van-area
        :area-list="areaList"
        title="选择上课区域"
        @cancel="showAddress = false"
        @confirm="onSelectAddress"/>
    </van-popup>

    <!-- 上课时间 -->
    <van-popup
      v-model="showTime"
      position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        type="datetime"
        @confirm="onSelectTime"
        @cancel="showTime = false"
        :min-date="minDate"
        :max-date="maxDate"/>
    </van-popup>
  </div>
</template>

<script>
import area from '@/assets/js/area'
import {datetimeFormat} from '@/utils'
import api from '@/api'
export default {
  name: 'edit-course',
  data () {
    return {
      course: {
        kech: '',
        kcname: '',
        student_id: '',
        type: '',
        skplace: '',
        class_hour: '',
        dqplace: ''
      },
      displayCourse: {
        type: '',
        students: '',
        repeat: ''
      },
      // profile_id是int课程id（编辑状态必填）
      showType: false,
      typeActions: [
        {name: '一对一VIP课程', value: 1},
        {name: '集体课程', value: 2}
      ],

      showRepeat: false,
      repeatActions: [
        {name: '每周', value: 1},
        {name: '隔周', value: 2},
        {name: '不重复', value: 3}
      ],

      showAddress: false,
      areaList: area,

      showTime: false,
      currentDate: new Date(),
      minDate: new Date(1900, 1, 1),
      maxDate: new Date(2100, 1, 1),
      timeType: 'start',

      displayTime: {
        start: ['10:00', '2019.09.01'],
        end: ['11:00', '2019.09.01']
      },
      start: '',
      end: '',
      id: '',
      profile_id: ''
    }
  },
  methods: {
    onSelectType (item) {
      this.course.kech = item.value
      this.displayCourse.type = item.name
      this.showType = false
    },
    onSelectRepeat (item) {
      this.course.type = item.value
      this.displayCourse.repeat = item.name
      this.showRepeat = false
    },
    onSelectAddress (arr) {
      let code = []
      let city = []
      arr.forEach(item => {
        code.push(item.code)
        city.push(item.name)
      })
      this.course.skplace = city.join(' ')
      this.showAddress = false
    },
    toSelectTime (type) {
      this.timeType = type
      if (type === 'start') {
        this.minDate = new Date()
        if (this.end) {
          this.maxDate = new Date(this.end)
        }
      } else if (type === 'end') {
        this.maxDate = new Date(2100, 1, 1)
        if (this.start) {
          this.minDate = new Date(this.start)
        }
      }
      this.showTime = true
    },
    onSelectTime (date) {
      let dateStr = datetimeFormat(date)
      this[this.timeType] = date.valueOf()
      let year = dateStr.split(' ')[0].split('-').join('.')
      let min = dateStr.split(' ')[1]
      this.displayTime[this.timeType] = [min, year]
      this.showTime = false
    },
    // cancel () {
    //   if (this.id) {
    //     this.$router.go(-1)
    //   } else {
    //     this.Dialog.confirm({
    //       title: '提示',
    //       message: '确定放弃该课程的编写吗？'
    //     }).then(() => {
    //       this.$router.go(-1)
    //     })
    //   }
    // },

    // 临时调课 agencyKechengUpdate
    toAddCourse () {
      // 添加教师id、上课开始结束时间（start，end）、状态（新增2，修改1）、修改id
      let params = JSON.parse(JSON.stringify(this.course))
      params.sktime = this.start / 1000
      params.xktime = this.end / 1000
      params.state = '2'
      params.id = this.$route.query.data
      if (this.id) {
        params.state = '1'
        params.profile_id = this.profile_id
      }
      api.agencyKechengUpdate({
        params,
        callback: res => {
          if (res.data.error_code === 0) {
            this.$toast({
              message: res.data.message,
              duration: 1000,
              forbidClick: true,
              onClose: () => {
                this.$router.go(-1)
              }
            })
          }
        }
      })
    },

    // 或取页面信息  agencyManagementCurriculum
    select () {
      let params = {
        id: this.$route.query.data
      }
      api.agencyManagementCurriculum({
        params,
        callback: res => {
          if (res.data.error_code === 0) {
            Object.keys(this.course).forEach(key => {
              if (res.data.data[key]) this.course[key] = res.data.data[key]
            })
            let stName = []
            let stId = []
            res.data.data.student.forEach(item => {
              stId.push(item.id)
              stName.push(item.name)
            })
            this.profile_id = res.data.data.profile_id
            this.course.student_id = stId.join(',')
            this.displayCourse.students = stName.join(',')
            res.data.data.type === 1 ? this.displayCourse.repeat = '每周' : (res.data.data.type === 2 ? this.displayCourse.repeat = '隔周' : this.displayCourse.repeat = '不重复')
            res.data.data.kech === 1 ? this.displayCourse.type = '一对一VIP课程' : this.displayCourse.type = '集体课程'
            this.start = Number(res.data.data.sktime) * 1000
            this.end = Number(res.data.data.xktime) * 1000
            let start = datetimeFormat(new Date(this.start))
            let end = datetimeFormat(new Date(this.end))
            this.displayTime.start = [start.split(' ')[1], start.split(' ')[0].split('-').join('.')]
            this.displayTime.end = [end.split(' ')[1], end.split(' ')[0].split('-').join('.')]
          }
        }
      })
    },
    // 获取学生列表
    toSelectStudent () {
      // /select/student/list
      sessionStorage.setItem('course', JSON.stringify(this.course))
      sessionStorage.setItem('displayCourse', JSON.stringify(this.displayCourse))
      sessionStorage.setItem('displayTime', JSON.stringify(this.displayTime))
      let cache = {
        start: this.start,
        end: this.end,
        profile_id: this.profile_id
      }
      sessionStorage.setItem('cache', JSON.stringify(cache))
      this.$router.push('/select/student/list')
    },
    getCourseDetail (id) {
      api.teacherCourseListDetail({
        params: {id},
        callback: res => {
          if (res.data.error_code === 0) {
            Object.keys(this.course).forEach(key => {
              if (res.data.data[key]) this.course[key] = res.data.data[key]
            })
            let stName = []
            let stId = []
            res.data.data.student.forEach(item => {
              stId.push(item.id)
              stName.push(item.name)
            })
            this.profile_id = res.data.data.profile_id
            this.course.student_id = stId.join(',')
            this.displayCourse.students = stName.join(',')
            res.data.data.type === 1 ? this.displayCourse.repeat = '每周' : (res.data.data.type === 2 ? this.displayCourse.repeat = '隔周' : this.displayCourse.repeat = '不重复')
            res.data.data.kech === 1 ? this.displayCourse.type = '一对一VIP课程' : this.displayCourse.type = '集体课程'
            this.start = Number(res.data.data.sktime) * 1000
            this.end = Number(res.data.data.xktime) * 1000
            let start = datetimeFormat(new Date(this.start))
            let end = datetimeFormat(new Date(this.end))
            this.displayTime.start = [start.split(' ')[1], start.split(' ')[0].split('-').join('.')]
            this.displayTime.end = [end.split(' ')[1], end.split(' ')[0].split('-').join('.')]
          }
        }
      })
    }
  },
  created () {
    this.select()
    let day = this.$route.query.day
    let start = this.$route.query.start + ':00'
    let end = this.$route.query.end + ':00'
    this.id = this.$route.query.id
    if (day) {
      this.displayTime.start = [start, day.split('/').join('.')]
      this.displayTime.end = [end, day.split('/').join('.')]
      this.start = new Date(`${day} ${start}`).valueOf()
      this.end = new Date(`${day} ${end}`).valueOf()
    }
    let studentList = JSON.parse(sessionStorage.getItem('studentList'))
    if (studentList) {
      sessionStorage.removeItem('studentList') // 先清除
      this.course = JSON.parse(sessionStorage.getItem('course'))
      this.displayCourse = JSON.parse(sessionStorage.getItem('displayCourse'))
      this.displayTime = JSON.parse(sessionStorage.getItem('displayTime'))
      let cache = JSON.parse(sessionStorage.getItem('cache'))
      this.start = cache.start
      this.end = cache.end
      this.profile_id = cache.profile_id
      let ids = []
      let names = []
      studentList.forEach(item => {
        ids.push(item.id)
        names.push(item.name)
      })
      this.course.student_id = ids.join(',')
      this.displayCourse.students = names.join(',')
    } else {
      if (this.id) {
        this.getCourseDetail(this.id)
      }
    }
  }
}
</script>

<style scoped>
  .van-cell{
    padding: 16px;
    color: #1E1E1E;
    font-family: PingFangBlod;
  }
  .van-cell .van-field{
    padding: 0;
  }
  .times{
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding-right: 16px;
  }
  .times img{
    margin: 0 16px;
  }
  .times .start-time{
    text-align: left;
  }
  .times .time p:nth-child(1){
    color: #1E1E1E;
    font-size: 16px;
    font-family: PingFangBlod;
  }
  .btns{
    margin-top: 40px;
  }
</style>
